package com.jt.provider.controller;

import com.jt.provider.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
public class ProviderSentinelController {

    @GetMapping("/provider/sentinel01")
    public String doSentinel01(){
        return "sentinel test 01";
    }

    @GetMapping("/provider/sentinel02")
    public String doSentinel02(){
        return "sentinel test 02";
    }

    @Autowired
    private ResourceService resourceService;
    @GetMapping("/provider/sentinel03")
    public String doSentinel03(){
       return resourceService.doGetResource();
       //return "sentinel test 03";
    }

    @GetMapping("/provider/sentinel04")
    public String doSentinel04(){
        resourceService.doGetResource();
        return "sentinel test 04";
    }
    //AtomicLong 是java.util.concurrent.atomic包中的线程安全对象
    //基于此对象实现自增，自减操作时，是线程安全的。
    private AtomicLong atomicLong=new AtomicLong(1);
    @GetMapping("/provider/sentinel05")
    public  String doSentinel05()throws Exception{
        Long count=atomicLong.getAndIncrement();//先取值，再加1
        if(count%2==0){
            //Thread.sleep(200);//模拟耗时操作
            throw new RuntimeException("exception ....");//模拟异常比例
        }
        return "sentinel test 05";
    }

    //http://localhost:port/provider/sentinel06?id=100
    @GetMapping("/provider/sentinel06")
//  @SentinelResource(value="selectById",
//                      blockHandlerClass = ResourceBlockHandler.class,
//                      blockHandler = "doHandle")
    public  String doSentinel06(@RequestParam("id") Integer id){
        ///..........
        return resourceService.doGetResource(id);
        //return "sentinel test 06,id="+id;
    }

}
